<template>
  <div class="prescription-container">

    <div v-if="!data.print " class="toolbar">
      <div>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button v-if="!view" type="primary" @click="save">保存</el-button>

      </div>
      <div v-if="data.pres_id">
        <el-button type="primary" @click="yb7101" :disabled="!(!data.hi_rxno && data.pres_id)">处方上传</el-button>
        <el-button type="primary" @click="yb7104" :disabled="!data.hi_rxno">处方撤消</el-button>
      </div>
    </div>
    <div class="body" :style="!data.print? 'margin-top: -3rem;':''">
      <!-- Header -->
      <div class="prescription-header">
        <div class="prescription-header-left">
          <div class="prescription-header-unit">{{ hosp.name }}</div>
          <div class="prescription-header-title">{{ title }}</div>
        </div>
        <div class="prescription-header-right">
          {{ prescriptionType }}
        </div>
      </div>
      <!-- 基本信息 -->
      <div class="prescription-info">
        <el-row v-if="!view" :gutter="0" class="edit">
          <el-col :span="12" class="el-col" style="justify-content: space-between;overflow: hidden;"><div><span class="label">No:</span><span>{{ data.pres_id }}</span></div></el-col>
          <el-col :span="12" class="el-col"><div class="label">医保备案编号：</div>{{ data.hi_rxno }}</el-col>
          <el-col :span="6" class="el-col"><div class="label">姓名：</div>{{ data.patient_name }}</el-col>
          <el-col :span="6" class="el-col"><div class="label">性别：</div>{{ data.patient_sex }}</el-col>
          <el-col :span="6" class="el-col"><div class="label">年龄：</div>{{ data.patient_age }}</el-col>
          <el-col :span="6" class="el-col"><div class="label">科别：</div>{{ data.sect_name }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">门诊病历号：</div>{{ data.patient_id }}</el-col>
          <el-col :span="16" class="el-col"><div class="label">开方日期：</div>{{ data.pres_date.substr(0,10) }}</el-col>
          <el-col :span="16" class="el-col"><div class="label">地址：</div>{{ data.patient_addr }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">电话：</div>{{ data.patient_contact_tel }}</el-col>
          <el-col :span="24" class="el-col" style="height: 2rem;"><div class="label">临床（初步）诊断及证型：</div>
            <el-select v-model="data.icds" value-key="value" size="small" multiple filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" style="width: calc(100% - 13rem);">
              <el-option v-for="item in diagnose" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
        </el-row>
        <el-row v-else :gutter="0" class="print">
          <el-col :span="24" class="el-col" style="justify-content: space-between;overflow: hidden;"><div><span class="label">No:</span><span>{{ data.pres_id }}</span></div><vue-barcode v-if="view" :value="data.pres_id" format="code128" displayValue="false" margin="0 0 0 auto" height="132" /></el-col>
          <el-col :span="8" class="el-col"><div class="label">姓名：</div>{{ data.patient_name }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">性别：</div>{{ data.patient_sex }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">年龄：</div>{{ data.patient_age }}</el-col>
          <el-col :span="16" class="el-col"><div class="label">门诊病历号：</div>{{ data.patient_id }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">科别：</div>{{ data.sect_name }}</el-col>
          <el-col :span="16" class="el-col"><div class="label">地址：</div>{{ data.patient_addr }}</el-col>
          <el-col :span="8" class="el-col"><div class="label">电话：</div>{{ data.patient_contact_tel }}</el-col>
          <el-col :span="24" class="el-col"><div class="label">临床（初步）诊断及证型：</div>
            <div v-if="view">{{ data.icdnames }}</div>
          </el-col>
          <el-col :span="8" class="el-col"><div class="label">开方日期：</div>{{ data.pres_date.substr(0,10) }}</el-col>
          <el-col :span="16" class="el-col"><div class="label">医保备案编号：</div>{{ data.hi_rxno }}</el-col>
        </el-row>
      </div>

      <!-- 处方内容 -->
      <div class="prescription-rp">Rp：</div>
      <div class="prescription-content">
        <!-- 编辑模式下 -->
        <el-table v-if="!view" class="edit" :data="data.list" :show-header="false" empty-text="无处方明细数据" border stripe height="240" max-height="240">
          <el-table-column width="0">
            <template slot-scope="scope">
              <div class="durg-content">
                <div class="first-line">
                  <div class="durg-index">{{ scope.$index+1 }}</div>
                  <div class="durg-name">{{ scope.row.name }}</div>
                  <div class="durg-spec">{{ scope.row.spec }}</div>
                  <div class="durg-quantity">
                    数量：
                    <el-input-number v-model="scope.row.quantity" size="mini" :min="1" :max="1000" :step="1" :controls="true" style="width: 5rem;" controls-position="both" @change="quantityChange(scope.$index, scope.row)" />
                    {{ scope.row.unit_name }}
                  </div>
                </div>
                <div class="second-line">
                  <div class="durg-dosage">
                    用量：
                    <el-input-number v-model="scope.row.medi_doage" size="mini" :min="1" :max="100" :step="1" controls-position="right" style="width:5rem;"/>
                    {{ scope.row.medi_unit_name }}/次
                  </div>
                  <div class="durg-medi-pass" style="overflow: hidden;">
                    <el-select v-model="scope.row.medi_pass" filterable size="mini" placeholder="请选择">
                      <el-option v-for="item in mediPass" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                  <div class="durg-use-type">
                    <el-select v-model="scope.row.use_type_id" filterable size="mini" placeholder="请选择">
                      <el-option v-for="item in useType" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                  <div class="zxts">
                    用药天数：
                    <el-input-number v-model="scope.row.zxts" size="mini" :min="1" :max="99" :step="1" controls-position="right" style="width:5rem;" />
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :width="60" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 打印模式下 -->
        <div v-else class="print">
          <div v-for="(item,i) in data.list" :key="i" class="line-box">
            <div class="line-index">{{ i+1 }}.</div>
            <div class="lines">
              <div class="line">
                <div>{{ item.name }}</div>
                <div>{{ item.spec }}</div>
                <div>{{ item.quantity }}{{ item.unit_name }}</div>
              </div>
              <div class="line">
                <div>用法：{{ item.medi_doage }}{{ item.medi_unit_name }}/次</div>
                <div>{{ item.medi_pass_name }}</div>
                <div>{{ item.use_type_name }}</div>
                <div>执行天数：{{ item.zxts }}天</div>
              </div>
            </div>
          </div>
        </div>
        <div class="empty-box" v-if="view && !data.pres_id">空白处方</div>
        <div v-if="view && data.pres_id" class="square" :style="`margin-bottom:${(5 - data.list.length) * 4}rem`"><div class="line" /></div>
      </div>
      <!-- Footer -->
      <div class="prescription-footer">
        <div class="prescription-footer-left">
          <div>药费</div>
          <div>￥{{ data.amount }}</div>
        </div>
        <div class="prescription-footer-center">
          <div>收费</div>
          <div>盖章</div>
        </div>
        <div class="prescription-footer-right">
          <div style="display:flex">医师(签名)：<div class="underline-text doctor">{{ data.doctor_name }}</div></div>
          <div style="display:flex">审核药师(签名)：<div class="underline-text" /></div>
          <div style="display:flex">配药药师(签名)：<div class="underline-text" /></div>
          <div style="display:flex">复核药师(签名)：<div class="underline-text" /></div>
        </div>
      </div>
      <div class="prescription-describe" style="display:flex;">
        <span>注意：请勿遗失，处方当日有效。因特殊情况，该处方有效期为</span>
        <el-input-number v-if="!view" v-model="data.valid_days" class="valid-days" size="mini" :min="3" :max="3" disabled controls-position="right" />
        <span v-else>{{ data.valid_days }}</span>
        <span>天</span>
      </div>
      <div style="text-align:left;font-size: 12px;">（签名：<span style="margin-left: 3rem">）</span></div>
    </div>
    <el-dialog
      title="医保电子处方撤消"
      :visible.sync="presCancelDialogVisible"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      width="30%">
      <div>
        <div style="text-align:left;margin-bottom: 0.5rem;">医保处方编号：{{ data.hi_rxno }}</div>
        <div style="text-align:left;margin-bottom: 0.5rem;">撤消原因：</div>
        <el-input v-model="undo_rea" type="textarea" :rows="5" placeholder="请输入撤消原因" style="width: 100%" />
      </div>
      <span slot="footer">
        <el-button @click="presCancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="presCancel">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VueBarcode from 'vue-barcode'
import { savePres } from '@/api/pres'
import { getHosp, mediPassList, useTypeList, diagList, chargeCatList } from '@/api/base'
import { yb7101, yb7104 } from '@/api/zjyb.js'
export default {
  name: 'Prescription',
  components: { VueBarcode },
  props: {
    data: {
      type: Object,
      default: () => ({
        pres_date: '2024-01-01 12:12:12'
      })
    },
    view: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hosp: { name: '杭州秋实健康管理有限公司萧山江寺诊所' },
      title: '普通处方笺（外配）',
      prescriptionType: '普通处方',
      useType: [],
      mediPass: [],
      diagnose: [],
      chargeCat: [],
      presCancelDialogVisible: false, // 医保电子处方撤消对话框
      undo_rea:'', // 撤销原因
    }
  },
  mounted() {
    this.initHosp()
    this.initMediPass()
    this.initUseType()
  },
  methods: {
    initHosp() {
      getHosp().then(res => {
        this.hosp = res.data
      })
    },
    initMediPass() {
      mediPassList().then(res => {
        this.mediPass = res.data.dataList
      })
    },
    initUseType() {
      useTypeList().then(res => {
        this.useType = res.data.dataList
      })
    },
    initDiagnose(query) {
      diagList({ keyword: '', codeList: query }).then(res => {
        this.diagnose = res.data.dataList
      })
    },
    async icdsChange(val){
      const icdnames = []
      await diagList({ keyword: '', codeList: val}).then(res => {
        const diagnose = res.data.dataList
        val.forEach(code => {
          const item = diagnose.find(i => i.value === code)
          if (item) {
            icdnames.push(item.label)
          }
        })
        this.data.icdnames = icdnames.join(',')
      })
    },
    initChargeCat() {
      chargeCatList().then(res => {
        this.chargeCat = res.data.dataList
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        diagList({ keyword: query, codeList: [] }).then(res => {
          this.diagnose = res.data.dataList
        })
      } else {
        this.diagnose = []
      }
    },
    handleDelete(index, row) {
      this.$emit('deleteRow',  { index, row })
    },
    quantityChange(index, row) {
      this.$emit('quantityChange', { index, row })
    },
    async print() {
      if (this.view) {
        // 查看模式
        if (this.data.pres_id) {
          localStorage.setItem('pres', JSON.stringify(this.data))
          window.open(this.$router.resolve({ path: '/prescription/print', query: { prescriptionNo: this.data.prescriptionNo }}).href, '_blank')
        } else {
          this.$message.error('空白处方，无法打印！')
        }
      } else {
        // 编辑模式，先保存再打开
        if (this.data.icds.length === 0) {
          this.$message('未选择临床（初步）诊断及证型，至少选择一项')
        } else if (this.data.list.length === 0) {
          this.$message('处方内容不能为空')
        } else {
          await this.icdsChange(this.data.icds)
          await savePres(this.data).then(res => {
            this.data.pres_id = res.data.pres_id
            this.$emit('afterSavePres', this.data )
            localStorage.setItem('pres', JSON.stringify(this.data))
            window.open(this.$router.resolve({ path: '/prescription/print', query: { prescriptionNo: this.data.prescriptionNo }}).href, '_blank')
          })
        }
      }
    },
    async save() {
      if (this.data.icds.length === 0) {
        this.$message('未选择临床（初步）诊断及证型，至少选择一项')
      } else if (this.data.list.length === 0) {
        this.$message('处方内容不能为空')
      } else {
        await this.icdsChange(this.data.icds)
        await savePres(this.data).then(res => {
          this.data.pres_id = res.data.pres_id
          this.$message.success('保存成功')
          this.$emit('afterSavePres', this.data )
        })
      }
    },
    async yb7101() {
      const _this = this
      await yb7101({ pres_id: this.data.pres_id }).then(res => {
        _this.data.hi_rxno = res.data.output.data.hi_rxno
        _this.data.rx_trace_code = res.data.output.data.rx_trace_code
        _this.$forceUpdate()
        _this.$message.success(`医保电子处方上传${res.msg}` )
      })
    },
    yb7104() {
      this.presCancelDialogVisible = true
    },
    presCancel() {
      const _this = this
      yb7104({ pres_id: this.data.pres_id, hi_rxno: this.data.hi_rxno, undo_rea: this.undo_rea }).then(res => {
        _this.data.hi_rxno = ''
        _this.data.rx_trace_code = ''
        _this.data.undo_rea = _this.undo_rea
        _this.presCancelDialogVisible = false
        _this.$message.success('撤消成功')
        _this.$forceUpdate()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.prescription-container {
  text-align: center;
  width: 100%;
  flex-direction: column;
  overflow-y: auto;
  .toolbar{
    position: relative;
    display: flex;
    align-items: left;
    margin-bottom: 1rem;
    // position: absolute;
    z-index: 1000;
    top: 0;
    justify-content: space-between;
  }
  .body{
    .prescription-header{
      display: flex;
      width: 100%;
      justify-content: space-between;
      &-left{
        display:inline;
        justify-content: space-between;
        align-items: center;
        width: calc(100% - 5rem);
        font-size: 1rem;
      }
      &-right{
        display: flex;
        justify-content: center;
        align-items: right;
        width: 3.5rem;
        height: 3.625rem;
        padding: 0.25rem;
        font-size: 1.25rem;
        border: 2px solid #000;
      }
    }
    .prescription-info{
      .edit {
        .el-col {
          font-size: 12px;
          display: flex;
          margin: 0.125rem 0;
          line-height: 1rem;
          height: 1rem;
          .label {
            margin: auto 0.5rem auto 0;
            font-weight: 400;
          }
        }
      }
      .print {
        .el-col {
          font-size: 12px;
          display: flex;
          margin: 0.125rem 0;
          line-height: 14px;
          height: 14px;
          .label {
            margin: auto 0.5rem auto 0;
            font-weight: 600;
          }
        }
      }
    }
    .prescription-rp{
      font-size: 1.125rem;
      font-weight: 600;
      text-align: left;
      margin-top: 0.125rem;
    }
    .prescription-content{
      margin: 0.5rem 0;
      .edit{
        font-size: 12px;
        width: 100%;
        .durg-content{
          .first-line{
            display: flex;
            justify-content: space-between;
            .durg-index {
              text-decoration: underline;
              text-align: center;
            }
            .durg-name {
              text-align: left;
              overflow-x: hidden;
            }
            .durg-spec {
              text-align: left;
              overflow-x: hidden;
            }
            .durg-quantity {
              text-align: center;
            }
          }
          .second-line{
            display: flex;
            margin-left: 3rem;
            margin-top: 0.5rem;
            justify-content: space-between;
            .durg-dosage{
              text-align: left;
              overflow: hidden;
              width: 30%;
            }
            .durg-medi-pass{
              text-align: left;
              overflow: hidden;
              width: 20%;
            }
            .durg-use-type{
              text-align: left;
              overflow: hidden;
              width: 20%;
            }
            .zxts{
              text-align: center;
              width: 30%;
            }
          }
        }

      }
    
      .print{
        width: 100%;
        font-size: 12px;
        .line-box {
          display: flex;
          .line-index {
            width: 3rem;
            font-size: 1.5rem;
            text-decoration: underline;
            text-align: center;
            margin: auto 0;
            line-height: 3rem;
          }
          .lines{
            width: calc(100% - 2rem);
            .line{
              width: 100%;
              display: flex;
              line-height: 1.5rem;
              justify-content: space-between;
            }
          }
        }
      }
      .square {
        height: 3rem;
        overflow: hidden;
        margin-top: 1rem;
        .line{
          height: 1px;
          border: 1px solid #000;
          transform: rotate(165deg);
        }
      }
    }
    .prescription-footer{
      display: flex;
      justify-content: space-between;
      align-items: center;
      &-left{
        display: flex;
        width: 8rem;
        justify-content: space-between;
        align-items: center;
        border: 2px solid #000;
        line-height: 3rem;
        font-size: 1rem;
        font-weight: bold;
        padding: 0 1rem;
      }
      &-center {
        flex-direction: column;
      }
      &-right {
        font-size: 12px;
        text-align: left;
        line-height: 1.25rem;
        overflow-x: hidden;
        .underline-text {
          width: 6rem;
          border-bottom: 2px solid black;
        }
        .doctor {
          width: 7.5rem;
        }
      }
    }
    .prescription-describe{
      text-align: left;
      line-height: 1rem;
      margin-top: 1rem;
      font-size: 12px;
      .valid-days{ 
        width: 5rem;
        margin: -0.5rem 0.5rem 0 0.5rem;
      }
    }
  }
  .empty-box {
    line-height: 15rem;
    font-size: 3rem;
    color: #ccc;
    text-align: center;
  }
}
</style>
